package com.example.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import com.example.User;
import com.example.SortedListOf;
import com.google.common.collect.Lists;

public class UserPage extends InternalPage {
	@FindBy(name = "username")
	public WebElement usernameField;

	@FindBy(name = "password")
	public WebElement passwordField;
	
	@FindBy(name = "password2")
	public WebElement passwordConfirmationField;

	@FindBy(name = "email")
	public WebElement emailField;
	
	@FindBy(name = "submit")
	public WebElement saveButton;

	@FindBy(xpath = ".//*[@id='content']/section/div[2]/table/tbody/tr")
	public List<WebElement> userRows;
	
	public boolean IsOnThisPage()	{
	return emailField.isDisplayed();
	}
	
	  private SortedListOf<User> cachedUsers;
	  
	  public SortedListOf<User> getUsers1() {
	    if (cachedUsers == null) {
	      cachedUsers = new SortedListOf<User>();
	      for (WebElement row : userRows) {
	        cachedUsers.add(conwertRowToUser(row));
	      }
	    }
        // return copy cachedListUsers
	    return new SortedListOf<User>(cachedUsers);
	  }
	  
	  public int getUserCount() {
	    return userRows.size();
	  }

	
	public UserPage createUser(User user) {
	    usernameField.sendKeys(user.name);
	    emailField.sendKeys(user.email);
	    passwordField.sendKeys(user.password);
	    passwordConfirmationField.sendKeys(user.password);
	    saveButton.click();
	    cachedUsers = null;
		return MyPageFactory.getPage(driver, UserPage.class);
	}

	public UserPage deleteUser(User user) {
		for (WebElement row : userRows ) {
			 if(user.equals(conwertRowToUser(row))) {
				row.findElement(By.xpath("./td[6]/a")).click();
			    wait_().until(alertIsPresent()).accept();
			    break;
			 }
		}	
	    cachedUsers = null;
		return MyPageFactory.getPage(driver, UserPage.class);
	}

	public List<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row : userRows ) {
			 users.add(conwertRowToUser(row));
		}	
		return users;
	}

	private User conwertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User()
	      .withname(cells.get(1).getText())
	      .withemail(cells.get(2).getText())
	      .withrole(cells.get(3).getText());
	}

	
}
